package com.saceem.imagenes;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

import com.saceem.dao.GenericDAO;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class SimpleConvertImage {
	private final static Logger log = Logger.getLogger(SimpleConvertImage.class
			.getName());

	// Este es el main original con el cual manejo imagenes menos TIFF
	// public static void main(String[] args) throws IOException {
	// String dirName = "C:\\Users\\Public\\Pictures\\Sample Pictures";
	// ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
	//
	// FileSeekableStream is = new FileSeekableStream(new File(dirName,
	// "06020014126_2.tif"));
	//
	// BufferedImage img = ImageIO
	// .read(new File(dirName, "06020014126_2.tif"));
	// ImageIO.write(img, "jpg", baos);
	// baos.flush();
	//
	// String base64String = Base64.encode(baos.toByteArray());
	// baos.close();
	//
	// System.out.println(base64String);
	// byte[] bytearray = Base64.decode(base64String);
	//
	// BufferedImage imag = ImageIO.read(new ByteArrayInputStream(bytearray));
	// ImageIO.write(imag, "jpg", new File(dirName, "06020014126_222.jpg"));
	//
	// // Esto es para probar guardar el campo en la base de Oracle, para el
	// // usuario de ReportesWeb
	// // saveImage("C:\\Users\\Public\\Pictures\\Sample Pictures",
	// // "Koala.jpg");
	// }

	public static void main(String[] args) throws IOException {
		String dirName = "C:\\Users\\Public\\Pictures\\Sample Pictures";

		File fInputFile = new File(dirName, "06020014126.tif");

		ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
		
		BufferedImage bi = getImageTiff(fInputFile);

		// BufferedImage img = ImageIO.read(fInputFile);// file
		// ImageIO.write(img, "jpg", baos);
		ImageIO.write(bi, "tif", baos);
		baos.flush();

		String base64String = Base64.encode(baos.toByteArray());
		baos.close();

		System.out.println(base64String);
		byte[] bytearray = Base64.decode(base64String);

		BufferedImage imag = ImageIO.read(new ByteArrayInputStream(bytearray));
		ImageIO.write(imag, "gif", new File(dirName, "06020014126.gif"));

		// Esto es para probar guardar el campo en la base de Oracle, para el
		// usuario de ReportesWeb
		// saveImage("C:\\Users\\Public\\Pictures\\Sample Pictures",
		// "Koala.jpg");
	}

	/**
	 * @param fInputFile
	 * @return
	 */
	private static BufferedImage getImageTiff(File fInputFile) {
		BufferedImage bi = null;
		ImageReadParam readParam = null;
		ImageReader rdr = null;
		Iterator itr = null;
		try {
//			itr = ImageIO.getImageReaders(ImageIO
//					.createImageInputStream(fInputFile));
			
			ImageInputStream iis = ImageIO.createImageInputStream(fInputFile);

			itr = ImageIO.getImageReaders(iis);
			
			if (!itr.hasNext()) {
				return null;
			}

			rdr = (ImageReader) itr.next();
			rdr.setInput(ImageIO.createImageInputStream(fInputFile));
			readParam = rdr.getDefaultReadParam();
			// readParam.setSourceRegion(new Rectangle(0, 0, 300, 300));
			if (true)
				bi = rdr.read(rdr.getMinIndex(), readParam);
			else
				bi = rdr.read(rdr.getMinIndex());

		} catch (IOException excp) {
			System.err.println(excp);
			return null;
		}
		return bi;
	}

	public String sendImage(String name) {
		try {
			ByteArrayOutputStream baos = getImageBaos(
					"C:\\Users\\Public\\Pictures\\Sample Pictures", "Koala.jpg");
			String base64String = Base64.encode(baos.toByteArray());
			baos.close();
			return base64String;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	private ByteArrayOutputStream getImageBaos(String path, String fileName)
			throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
		BufferedImage img;
		img = ImageIO.read(new File(path, "fileName"));
		ImageIO.write(img, "jpg", baos);
		baos.flush();

		return baos;
	}

	public static void saveImage(String path, String fileName) {
		// System.out.println("file data " + upload);
		// System.out.println("After " + upload);
		log.info(" saveImage()");
		Connection cnn = null;

		Date d = new Date(System.currentTimeMillis());

		try {
			GenericDAO objGenericDao = GenericDAO.getInstance();
			cnn = objGenericDao.getRepoTotvsConnection();

			PreparedStatement pstmt = cnn
					.prepareStatement("INSERT INTO imagenes VALUES (?,?,?)");
			File fBlob = new File(path, fileName);
			FileInputStream is = new FileInputStream(fBlob);
			pstmt.setString(1, fileName);
			pstmt.setBinaryStream(2, is, (int) fBlob.length());
			pstmt.setDate(3, d);
			pstmt.executeUpdate();
			log.info("Imagen guardada.");

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			log.error("NamingException en el metodo saveImage(): "
					+ e.getMessage());
		} catch (FileNotFoundException e) {
			log.error("FileNotFoundException en el metodo saveImage(): "
					+ e.getMessage());
		} finally {
			try {
				cnn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

}
